<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome'}">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="添加商品信息" type="info"></el-alert>

      <el-steps :space="200" :active="activeName-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="动态参数"></el-step>
        <el-step title="静态参数"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 只有一个el-form 一个表单 拆分多个tag-pane面板  -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef">
        <el-tabs v-model="activeName" tab-position="left" :before-leave="beforeLeave" @tab-click="handleTabClick">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input type="number" v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input type="number" v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-cascader @change="handleChange" clearable v-model="addForm.goods_cat" :options="cateList"
                :props="{ expandTrigger: 'hover',label:'cat_name',value:'cat_id' }">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数(动态)" name="1">
            <el-form-item v-for="item in manyTableData" :key="item.attr_id" :label="item.attr_name">
              <br>
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :label="item1" v-for="(item1,index1) in item.attr_vals1" :key="index1">
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性(静态)" name="2">
            <el-form-item v-for="item in onlyTableData" :key="item.attr_id" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload :headers="headersObj" class="upload-demo"
              action="http://42.192.71.221:8889/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              list-type="picture"
              :on-success="handleSuccess">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button @click="addGoods" style="margin: 15px 0;" type="primary">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 预览图片的对话框 -->
    <el-dialog
      :visible.sync="previewImgDialog"
      width="50%">
      <img style="width: 100%;" :src="imgUrl" />
    </el-dialog>
  </div>
</template>

<script>
import { cloneDeep } from 'lodash'
export default {
  data () {
    return {
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      fileList: [],
      onlyTableData: [],
      manyTableData: [],
      cateList: [],
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_cat: [1, 3, 6],
        pics: [],
        goods_introduce: ''
      },
      addFormRules: {
        goods_name: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ]
      },
      activeName: '0',
      previewImgDialog: false, // 控制图片预览对话框显示隐藏
      imgUrl: '' // 预览图片地址
    }
  },
  methods: {
    handleSuccess (response) {
      // console.log(response)
      this.addForm.pics.push({
        pic: response.data.tmp_path
      })
    },
    // 点击文件列表进行预览触发
    handlePreview ({ response: { data } }) {
      console.log(data)
      this.imgUrl = 'http://42.192.71.221:8889/' + data.tmp_path
      this.previewImgDialog = true
    },
    // 点击移除时触发
    handleRemove ({ response: { data } }) { // file { response: {} }
      const i = this.addForm.pics.findIndex(item => item.pic === data.tmp_path)
      this.addForm.pics.splice(i, 1)
    },
    async handleTabClick () {
      if (this.activeName === '1') {
        // 切换到动态参数
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'many' } })
        res.data.forEach(item => {
          item.attr_vals1 = item.attr_vals = item.attr_vals.split(' ')
        })
        this.manyTableData = res.data
        console.log(this.manyTableData)
      } else if (this.activeName === '2') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'only' } })
        this.onlyTableData = res.data
        console.log(this.onlyTableData)
      }
    },
    // to 去哪
    // from 来自哪里
    // // from sh to hz
    beforeLeave (to, from) {
      if (from === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请选择三级分类')
        // retrun false作用 阻止冒泡+阻止默认行为 e.preventDefault() e.stopPropagation()
        return false
      }
    },
    handleChange () {
      console.log(this.addForm.goods_cat)
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
        return
      }
      console.log('可以操作')
    },
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      this.cateList = res.data
    },
    // 点击添加商品
    addGoods () {
      // 实现表单校验
      this.$refs.addFormRef.validate(async flag => {
        if (!flag) return this.$message.error('亲,请填写必要的表单信息呦')
        // console.log(this.addForm)
        // 页面的数据 和 交给后台的数据 不一致
        // const form = this.addForm
        // form.goods_cat = form.goods_cat.join(',')
        // console.log(form === this.addForm)
        // 深拷贝 拷贝数据
        // 1. 递归函数
        // 2. JSON.stringify 转成字符串 在利用 JSON.parse还原json对象
        // const form = JSON.parse(JSON.stringify(this.addForm))
        // console.log(form, this.addForm)
        // console.log(form === this.addForm)
        // 3. 第三方包 lodash
        const form = cloneDeep(this.addForm)
        // 修改goods_cat数据格式
        form.goods_cat = form.goods_cat.join(',')

        form.attrs = []
        // 循环动态参数
        this.manyTableData.forEach(item => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(',')
          })
        })
        // 循环静态属性
        this.onlyTableData.forEach(item => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          })
        })

        // 发请求 传递数据
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) return this.$message.error('亲,创建失败了呦')
        this.$message.success('亲,创建成功')
        this.$router.go(-1)
      })
    }
  },
  computed: {
    cateId () {
      return this.addForm.goods_cat[2]
    }
  },
  watch: {},
  filters: {},
  components: {},
  created () {
    this.getCateList()
  },
  mounted () { }
}
</script>

<style scoped lang='less'>
// 深度选择器
// >>> ::v-deep 编译速度快  /deep/ vue3 会报错
/deep/ .el-step__title {
  font-size: 12px;
}

/deep/ .ql-editor {
  height: 240px;
}
</style>
